package com.eagle.gennewdata.logic;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.InputSource;

import com.eagle.gennewdata.model.NewDaoFactory;
import com.eagle.gennewdata.model.NewRssItem;
import com.eagle.gennewdata.untl.ZLibUtils;

public class NewDataImpl implements INewData {

	public static List<String> m_arrTitleList = new ArrayList<String>();
	
	public void PaserXmlUrl(String strUrl) {
		// TODO Auto-generated method stub
		try {
			URL url = new URL(strUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url
					.openConnection();
			httpConn.setReadTimeout(1000 * 60);
			InputStreamReader inputStream = new InputStreamReader(
					httpConn.getInputStream(), "UTF-8");
			PaserRssXmlStream(inputStream);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void PaserXmlStream(InputStream inputStreamIO) {
		// TODO Auto-generated method stub
		InputStreamReader inputStreamReader;
		try {
			inputStreamReader = new InputStreamReader(inputStreamIO, "UTF-8");
			PaserRssXmlStream(inputStreamReader);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void PaserXmlByteArray(byte[] byteXml) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(new ByteArrayInputStream(byteXml));
			PaserRssXmlDocument(doc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void PaserRssXmlDocument(Document doc) {
		try {
			Element rootElement = doc.getDocumentElement();
			if (rootElement == null)
				return;

			String strAuthor = "";
			String strLogo = "";
			String strParentUrl = "";

			NodeList pchannel = doc.getElementsByTagName("title");
			if (pchannel != null) {
				Node nodeChannel = pchannel.item(0);
				strAuthor = nodeChannel.getTextContent();
			}

			pchannel = doc.getElementsByTagName("link");
			if (pchannel != null) {
				Node nodeChannel = pchannel.item(0);
				strParentUrl = nodeChannel.getTextContent();
			}

			pchannel = doc.getElementsByTagName("logo");
			if (pchannel != null) {
				Node nodeChannel = pchannel.item(0);
				strLogo = nodeChannel.getTextContent();
			}

			NodeList paramNodeLists = doc.getElementsByTagName("item");
			int iNodeCount = paramNodeLists.getLength();
			for (int i = 0; i < iNodeCount; i++) {
				Node node = paramNodeLists.item(i);
				NewRssItem itemAdd = new NewRssItem();
				itemAdd.setAuthor(strAuthor);
				itemAdd.setParentUrl(strParentUrl);
				itemAdd.setLogo(strLogo);
				NodeList childNodeList = node.getChildNodes();
				for (int j = 0; j < childNodeList.getLength(); j++) {
					Node nodeNew = childNodeList.item(j);
					if (nodeNew.getNodeName().equalsIgnoreCase("title"))
						itemAdd.setNewTitle(nodeNew.getTextContent().trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase("link"))
						itemAdd.setLink(nodeNew.getTextContent().trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase("category"))
						itemAdd.setCategory(nodeNew.getTextContent().trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase(
							"description"))
						itemAdd.setNewDescription(nodeNew.getTextContent()
								.trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase("pubDate"))
						itemAdd.setInputDate(nodeNew.getTextContent().trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase("guid"))
						itemAdd.setGuid(nodeNew.getTextContent().trim());
					else if (nodeNew.getNodeName().equalsIgnoreCase(
							"content:encoded")) {
						if (!nodeNew.getTextContent().equals(""))
							itemAdd.setContentEncoded(ZLibUtils
									.compress(nodeNew.getTextContent().trim()
											.getBytes("UTF-8")));
					} else if (nodeNew.getNodeName().equalsIgnoreCase("logo"))
						itemAdd.setLogo(nodeNew.getTextContent().trim());
				}
				if (IsRssItemExist(itemAdd.getNewTitle()) == false)
				{
					NewDaoFactory.insertAndUpdateNewData(itemAdd);
					m_arrTitleList.add(itemAdd.getNewTitle());
				}
			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
			// TODO: handle exception
		}
	}

	private boolean IsRssItemExist(String strTitle)
	{
		Boolean bFindBoolean = false;
		for(String strItem : m_arrTitleList)
			if (strItem.equalsIgnoreCase(strTitle))
				bFindBoolean = true;
		
		if (m_arrTitleList.size() > 50) 
			for (int i = 50; i > 30; i--)
				m_arrTitleList.remove(i);
		
		return bFindBoolean;
	}
	
	private void PaserRssXmlStream(InputStreamReader inputStream) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setValidating(false);
			DocumentBuilder doc_builder = dbf.newDocumentBuilder();
			Document doc = (Document) doc_builder.parse(new InputSource(
					inputStream));
			PaserRssXmlDocument(doc);
		} catch (Exception e) {
			System.out.print(e.getMessage());
			// TODO: handle exception
		}
	}

	public static String getContent(String strUrl) {

		try {
			URL url = new URL(strUrl);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					url.openStream(), "UTF-8"));
			String s = "";
			StringBuffer sb = new StringBuffer("");
			while ((s = br.readLine()) != null) {
				sb.append(s + "\r\n");
			}
			br.close();
			return sb.toString();
		} catch (Exception e) {
			return "error open url:" + strUrl;
		}
	}

}
